﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RoboServ
{
    class XBeeRequest : XBeeMessage
    {
        public const byte REQ_AT_LOCAL = 0x08;
        public const byte REQ_AT_REMOTE = 0x17;
        public const byte REQ_TX_16BIT = 0x01;
        public const byte REQ_TX_64BIT = 0x00;

        public XBeeRequest(byte apiID, byte msgID, byte[] data)
        {
            this.apiID = apiID;
            this.msgID = msgID;
            this.data = data;
        }

        public byte[] getFullMessage()
        {
            byte[] ret = new byte[getLength()];

            ret[0] = apiID;
            ret[1] = msgID;

            int curByte = 2;

            if (use64BitAddress)
            {
                byte[] addr = Utils.UInt64ToBytes(address64);

                Utils.addArrayToArray(ret, addr, curByte);
                curByte += 8;
            }

            if (use16BitAddress)
            {
                byte[] addr = Utils.UInt16ToBytes(address16);

                Utils.addArrayToArray(ret, addr, curByte);
                curByte += 2;
            }

            Utils.addArrayToArray(ret, data, curByte);

            return ret;
        }

        public byte calcChecksum()
        {
            return (byte)(0xFF - (getMessageSum() % 0xFF));
        }

        public byte[] buildRequest()
        {
            byte[] fullMsg = getFullMessage();

            byte[] request = new byte[fullMsg.Length + 4];

            request[0] = XBeeSerial.API_PACKET_START;

            byte[] msgLen = Utils.UInt16ToBytes((UInt16)fullMsg.Length);

            request[1] = msgLen[0];
            request[2] = msgLen[1];

            for (int i = 0; i < fullMsg.Length; i++)
                request[i + 3] = fullMsg[i];

            request[request.Length - 1] = calcChecksum();

            return request;
        }
    }
}
